package com.firefly.job.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @description:启动定时任务
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/6/1
 **/
@Configuration
@Slf4j
public class QuartzConfiguration implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    @Lazy // 循环依赖了
    private QuartzSchedulerManager quartzSchedulerManager;

    @Autowired
    private QuartzJobFactory quartzJobFactory;

    // 初始启动quartz
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            quartzSchedulerManager.startJob();
            log.info("任务已经启动...");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(true);
        // 自定义Job Factory，用于Spring注入
        factory.setJobFactory(quartzJobFactory);
        return factory;
    }

    // 初始注入scheduler
    @Bean
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }
}
